package com.free.bsf.message.channel;

import com.free.bsf.core.http.DefaultHttpClient;
import com.free.bsf.core.http.HttpClient;
import lombok.Data;
import org.apache.http.entity.ContentType;

import java.net.SocketTimeoutException;


/**
 * @author: huojuncheng
 * @version: 2020-08-25 15:10
 **/
@Data
public class FlyBookProvider extends AbstractMessageProvider {
    @Override
    protected String getName(){
        return "flybook";
    }

    String url = "https://open.feishu.cn/open-apis/bot/hook/{access_token}";

    @Override
    public void sendText(String text){
        if(!isEnabled())
            return;
        getTokens().forEach(t->{
        FlyBookBody.Text text1 = new FlyBookBody.Text();
        text1.setText(text);
        FlyBookBody flyBookBody = new FlyBookBody();
        flyBookBody.setText(text1);
        flyBookBody.setMsgtype("text");
        HttpClient.Params params = HttpClient.Params.custom().setContentType(ContentType.APPLICATION_JSON).add(flyBookBody.text).build();
        try {
            DefaultHttpClient.Default.post(getUrl().replace("{access_token}", t), params);
        }catch (Exception e){
            if(e.getCause() instanceof SocketTimeoutException)
            {
                //网关不一定稳定
                return;
            }
            throw e;
        }});
    }

    @Data
    public static class FlyBookBody
    {
        @Data
        public static class MarkDown
        {
            private String title;
            private String text;
        }
        @Data
        public static class Text
        {
            private String text;
        }
        /**
         * "markdown","text"
         */
        private String msgtype="markdown";
        private MarkDown markdown;
        private Text text;
    }
}
